package com.esl.coordinator.util;

import java.math.BigInteger;

import javax.xml.bind.DatatypeConverter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class Hex {
	static final Logger LOG = LoggerFactory.getLogger(Hex.class);

	public static String toHexString(byte[] bytes) {
		BigInteger bi = new BigInteger(1, bytes);
		return String.format("%0" + (bytes.length << 1) + "X", bi);
	}

	public static String toHexString(int number) {
		StringBuffer hexStr = new StringBuffer(Integer.toHexString(number));
		if (hexStr.length() % 2 == 1) {
			hexStr.insert(0, "0");
		}
		return hexStr.toString().toUpperCase();
	}

	public static String toHexStringWithPadding(int number, int totalBytes) {
		StringBuffer hexStr = new StringBuffer(Integer.toHexString(number));
		int i = hexStr.length();
		while (i < totalBytes * 2) {
			hexStr.insert(0, "0");
			i++;
		}
		return hexStr.toString().toUpperCase();
	}

	public static byte[] toHexBytes(String hexStr) {
		return DatatypeConverter.parseHexBinary(hexStr);
	}
}
